package com.ruoyi.js.utils;

import com.ruoyi.common.utils.DateUtils;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.filters.ImageFilter;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageUtils {

    // 通过修改图片质量递归压缩图片大小
    public static String reduceImage(String sourcePath, double outputQuality, int targetLength) throws IOException {
        // 只支持.png .jpg .jpeg
        if(!sourcePath.endsWith(".png") && !sourcePath.endsWith(".jpg") && !sourcePath.endsWith(".jpeg")){
            return sourcePath;
        }
        String thumbPath = sourcePath + "_thumb.jpg";
        File sourceFile = new File(sourcePath);
        if(sourceFile.exists()){
            if(!sourcePath.endsWith("png")){
                Thumbnails.of(sourcePath).addFilter(new ThumbnailsImgFilter()).scale(1).outputQuality(outputQuality).outputFormat("jpg").toFile(thumbPath);
            }else {
                Thumbnails.of(sourcePath).scale(1).outputQuality(outputQuality).outputFormat("jpg").toFile(thumbPath);
            }
            File thumbFile = new File(thumbPath);
            if(outputQuality > 0.1 && thumbFile.length() > targetLength){
                if(sourceFile.length() > 2 * targetLength && outputQuality > 0.6){
                    outputQuality = 0.6;
                }else {
                    outputQuality -= 0.1;
                }
                reduceImage(sourcePath, outputQuality, targetLength);
            }else {
                System.out.println(DateUtils.getTime() + ">>>>" + sourcePath + ">>>>" + thumbPath + ">>>>" + outputQuality);
            }
        }
        return  thumbPath;
    }

    public static class ThumbnailsImgFilter implements ImageFilter {

        @Override
        public BufferedImage apply(BufferedImage img) {
            int w = img.getWidth();
            int h = img.getHeight();
            BufferedImage newImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = newImg.createGraphics();
            g2d.setColor(Color.white);
            g2d.fillRect(0, 0, w, h);
            g2d.drawRenderedImage(img, null);
            g2d.dispose();
            return newImg;
        }
    }

}
